package top.yxf.springboot.drools.utils;

import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.kie.api.builder.Message;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieSession;
import org.kie.internal.utils.KieHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import top.yxf.springboot.drools.entity.Rule;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * @author xs.wu
 */
public class KieSessionUtil<T> {

    Logger logger = LoggerFactory.getLogger(KieSessionUtil.class);

    /**
     * 把xls文件解析为String
     * @param realPath
     * @return
     * @throws FileNotFoundException
     */
    public static String getDRL (String realPath) throws FileNotFoundException {
        // 例如：C:\\abc.xls
        File file = new File(realPath);
        InputStream is = new FileInputStream(file);
        SpreadsheetCompiler compiler = new SpreadsheetCompiler();
        String drl = compiler.compile(is, InputType.XLS);
        System.out.println(drl);
        return drl;
    }

    /**
     * drl为含有内容的字符串
     * @param drl
     * @return
     * @throws Exception
     */
    public static KieSession createKieSessionFromDRL(String drl) throws Exception{
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(drl, ResourceType.DRL);
        Results results = kieHelper.verify();
        if (results.hasMessages(Message.Level.WARNING, Message.Level.ERROR)) {
            List<Message> messages = results.getMessages(Message.Level.WARNING, Message.Level.ERROR);
            for (Message message : messages) {
                System.out.println("Error: "+message.getText());
            }
            // throw new IllegalStateException("Compilation errors were found. Check the logs.");
        }
        return kieHelper.build().newKieSession();
    }


    /**
     * realPath为Excel文件绝对路径
     * @param realPath
     * @return
     * @throws Exception
     */
    public static KieSession getKieSessionFromXLS(String realPath) throws Exception {
        return createKieSessionFromDRL(realPath);
    }


    /**
     * 执行对应的规则引擎
     * @param ruleList 规则集合
     * @param t 规则参数
     * @return
     */
    public T execute(List<Rule> ruleList, T t) {
        if (CollectionUtils.isEmpty(ruleList) || t == null) {
            return t;
        }
        logger.info("执行规则引擎 start ....");
        System.setProperty("drools.dateformat", "yyyy-MM-dd HH:mm:ss");
        KieHelper helper = new KieHelper();
        for (Rule rule : ruleList) {
            helper.addContent(rule.getRule(), ResourceType.DRL);
        }
        KieSession kSession = helper.build().newKieSession();
        kSession.insert(t);
        kSession.fireAllRules();
        kSession.dispose();
        logger.info("执行规则引擎 end ....");
        return t;
    }

}
